package com.lack.openApiClientSdk.Client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.lack.openApiClientSdk.model.User;


import java.util.HashMap;
import java.util.Map;

import static com.lack.openApiClientSdk.utils.SignUtil.genSign;


public class LackClient {
    /**
     * 秘钥
     */
    private String accessKey;


    /**
     * 秘钥
     */
    private String secretKey;

    public LackClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    private static final String URL = "http://localhost:8089";

    public String getNameByGet(String name) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result = HttpUtil.get(URL + "/api/name/", paramMap);
        System.out.println(result);
        return result;
    }

    public String getNameByPost(String name) {
        //可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        String result = HttpUtil.post(URL + "/api/name/", paramMap);
        System.out.println(result);
        return result;
    }

    private Map<String, String> getHeader(String body) {
        HashMap<String, String> headerMap = new HashMap<>();
        headerMap.put("accessKey", accessKey);
        //secretKey不能发送给服务端
//        header.put("secretKey", secretKey);
        headerMap.put("nonce", RandomUtil.randomNumbers(5));
        headerMap.put("body", body);
        headerMap.put("timeStamp", String.valueOf(System.currentTimeMillis()));
        headerMap.put("sign", genSign(body, secretKey));
        return headerMap;
    }

    public String getNameByPostJson(User user) {
        String json = JSONUtil.toJsonStr(user);
        String result = HttpRequest.post(URL + "/api/name/json/")
                .addHeaders(getHeader(json))
                .body(json)
                .execute().body();
        System.out.println(result);
        return result;
    }
}
